package top.blackr.folivora.common.security.crud.repository;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.repository.CrudRepository;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import top.blackr.folivora.common.security.auth.SecUser;
import top.blackr.folivora.common.security.auth.SecurityUtils;
import top.blackr.folivora.common.security.crud.mapper.SysDeptMapper;
import top.blackr.folivora.common.security.crud.model.entity.SysDept;
import top.blackr.folivora.common.security.crud.model.entity.SysDeptRelation;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
@AllArgsConstructor
public class SysDeptRepository extends CrudRepository<SysDeptMapper, SysDept> {

    private final SysDeptRelationRepository sysDeptRelationService;

    /**
     * 添加信息部门
     *
     * @param dept 部门
     * @return 成功、失败
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveDept(SysDept dept) {
        Integer parentId = dept.getParentId();
        SysDept parentDept = this.getById(parentId);
        if (ObjectUtil.isEmpty(parentDept)) {
            return Boolean.FALSE;
        }
        Integer lv = parentDept.getLv();
        SysDept sysDept = new SysDept();
        BeanUtils.copyProperties(dept, sysDept);
        sysDept.setLv(lv + 1);
        this.save(sysDept);
        // 保存关联关系
        sysDeptRelationService.insertDeptRelation(sysDept);
        return Boolean.TRUE;
    }

    /**
     * 删除部门
     *
     * @param id 部门 ID
     * @return 成功、失败
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeDeptById(Integer id) {
        if (id == 1) {
            return Boolean.FALSE;
        }
        // 级联删除部门
        List<Integer> idList = sysDeptRelationService
                .list(Wrappers.<SysDeptRelation>query().lambda().eq(SysDeptRelation::getAncestor, id)).stream()
                .map(SysDeptRelation::getDescendant).collect(Collectors.toList());

        if (CollUtil.isNotEmpty(idList)) {
            this.removeByIds(idList);
        }

        // 删除部门级联关系
        sysDeptRelationService.deleteAllDeptRelation(id);
        return Boolean.TRUE;
    }

    /**
     * 更新部门
     *
     * @param sysDept 部门信息
     * @return 成功、失败
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateDeptById(SysDept sysDept) {
        // 更新部门状态
        return this.updateById(sysDept);
    }

    public Object deptAuthority() {
        SecUser user = SecurityUtils.getUser();
        // 如果是超级管理员
        if (SecurityUtils.isAdmin()) {
            return selectTree();
        }
        Integer deptId = user.getDeptId();
        // 查询下级部门
        List<SysDept> deptAllList = baseMapper.selectList(Wrappers.<SysDept>lambdaQuery()
                .eq(SysDept::getParentId, deptId)
                .eq(SysDept::getDelFlag, 0));
        // 权限内部门
        List<TreeNode<Integer>> collect = this.getTreeNode(deptAllList);
        return TreeUtil.build(collect, deptId);
    }

    /**
     * 查询全部部门树
     *
     * @return 树
     */
    public List<Tree<Integer>> selectTree() {
        // 查询全部部门
        List<SysDept> deptAllList = baseMapper.selectList(Wrappers.<SysDept>lambdaQuery().eq(SysDept::getDelFlag, 0));
        // 权限内部门
        List<TreeNode<Integer>> collect = this.getTreeNode(deptAllList);

        return TreeUtil.build(collect, 0);
    }

    private List<TreeNode<Integer>> getTreeNode(List<SysDept> deptList) {
        return deptList.stream()
                .filter(dept -> dept.getDeptId().intValue() != dept.getParentId())
                .sorted(Comparator.comparingInt(SysDept::getSort)).map(dept -> {
                    TreeNode<Integer> treeNode = new TreeNode<>();
                    treeNode.setId(dept.getDeptId());
                    treeNode.setParentId(dept.getParentId());
                    treeNode.setName(dept.getName());
                    treeNode.setWeight(dept.getSort());
                    // 有权限不返回标识
                    Map<String, Object> extra = new HashMap<>(8);
                    extra.put("createTime", dept.getCreateTime());
                    extra.put("lv", dept.getLv());
                    treeNode.setExtra(extra);
                    return treeNode;
                }).collect(Collectors.toList());
    }

}
